package com.htudata.zabbix.host.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htudata.core.util.operation.ArrayOperationUtils;
import com.htudata.core.util.operation.StringOperationUtils;
import com.htudata.zabbix.api.service.HostZabbixApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HostService {

  @Autowired
  private HostZabbixApiService hostZabbixApiService;
  
  public static boolean isValidHostId(String id) {
    if (StringOperationUtils.isPositiveInt(id))
      return true; 
    return false;
  }
  
  public JSONObject getHosts(String[] groupIdArr, String[] hostNameArr, int limit) throws Exception {
    JSONObject params = new JSONObject();
    params.put("preservekeys", Boolean.valueOf(true));
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("sortfield", "hostid");
    params.put("sortorder", "DESC");
    params.put("output", new String[] { "name", "status", "available" });
    if (ArrayOperationUtils.isValidArr((Object[])groupIdArr))
      params.put("groupids", groupIdArr); 
    params.put("selectParentTemplates", new String[] { "templateid", "name" });
    params.put("selectItems", "count");
    params.put("selectTriggers", "count");
    params.put("selectGraphs", "count");
    if (ArrayOperationUtils.isValidArr((Object[])hostNameArr)) {
      JSONObject search = new JSONObject();
      search.put("name", hostNameArr);
      params.put("search", search);
    } 
    String json = this.hostZabbixApiService.getHosts(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    try {
      JSONObject result = root.getJSONObject("result");
      return result;
    } catch (Exception e) {
      throw e;
    } 
  }
  
  public JSONArray getHostInfo(String[] hostIdArr, int limit) throws Exception  {
    JSONObject params = new JSONObject();
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("sortfield", "hostid");
    params.put("sortorder", "DESC");
    params.put("output", new String[] { "host", "name" });
    if (ArrayOperationUtils.isValidArr((Object[])hostIdArr))
      params.put("hostids", hostIdArr); 
    params.put("selectInterfaces", new String[] { "ip", "port" });
    params.put("selectParentTemplates", "count");
    params.put("selectItems", "count");
    params.put("selectTriggers", "count");
    params.put("selectGraphs", "count");
    String json = this.hostZabbixApiService.getHosts(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    JSONArray result = root.getJSONArray("result");
    return result;
  }
}
